package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.UserLikeApi;
import com.tanhua.dubbo.api.VisitorsApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ListVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @program: tanhua
 * @description: UserInfoService
 * @author: leiyukun
 * @create: 2022-03-23 15:41
 **/
@Service
public class UserInfoService {
    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    //更新用户头像
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        //1、将图片上传到阿里云oss
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2、调用百度云判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(imageUrl);
        //2.1 如果不包含人脸，抛出异常
        if (!detect) {
            throw new RuntimeException();
        } else {
            //2.2 包含人脸，调用API更新
            UserInfo userInfo = new UserInfo();
            userInfo.setId(id);
            userInfo.setAvatar(imageUrl);
            userInfoApi.update(userInfo);
        }
    }


    //更新
    public void update(UserInfo userInfo) {
        userInfoApi.update(userInfo);
    }

    //根据id查寻
    public UserInfoVo findById(Long id) {
        UserInfo userInfo = userInfoApi.findById(id);

        UserInfoVo vo = new UserInfoVo();

        BeanUtils.copyProperties(userInfo, vo); //copy同名同类型的属性

        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    public boolean Verification(String phone, String code) {
        //1、从redis中获取下发的验证码
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);
        //2、对验证码进行校验（验证码是否存在，是否和输入的验证码一致）
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //验证码无效
            return false;
        }
        //3、删除redis中的验证码
        redisTemplate.delete("CHECK_CODE_" + phone);
        return true;
    }

    public Map<String, Integer> findcounts() {
        Long userId = UserHolder.getUserId();
        return userLikeApi.findcounts(userId);
    }

    /**
     * 互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
     *
     * @param page
     * @param pagesize
     * @param type
     * @return
     */
    public PageResult findByType(Integer page, Integer pagesize, Integer type) {
        Long userId = UserHolder.getUserId();
        if (type != 4) {
            List<UserLike> list = userLikeApi.findType(userId, type);
            //3、提取用户的id
            List<Long> userIds = CollUtil.getFieldValues(list, "userId", Long.class);
            List<Long> touserIds = CollUtil.getFieldValues(list, "likeUserId", Long.class);
            List<RecommendUser> recommendUserList = recommendUserApi.findByIds(userIds, touserIds);
            //4、查看用户详情
            List<UserInfo> infos = userInfoApi.findByIdss(userIds);
            //5、构造返回
            List<ListVo> vos = new ArrayList<>();
            for (int i = 0; i < list.size()-1; i++) {

                if (infos.get(i)!= null) {
                    ListVo vo = ListVo.init(infos.get(i), list.get(i).getIsLike(), recommendUserList.get(i).getScore());
                    vos.add(vo);
                }
            }
            PageResult pr = new PageResult(page, pagesize, 0L, vos);
            return pr;
        } else {
            //1、查询访问时间
            String key = Constants.VISITORS_USER;
            String hashKey = String.valueOf(UserHolder.getUserId());

            redisTemplate.opsForHash().delete(key,hashKey);
            List<Visitors> visitors = visitorsApi.findMyVisitors(userId);
            List<Long> userIds = CollUtil.getFieldValues(visitors, "userId", Long.class);
            List<Long> touserIds = CollUtil.getFieldValues(visitors, "(visitorUserId", Long.class);
            Boolean aBoolean = userLikeApi.judge(userIds, touserIds);
            //4、查看用户详情
            List<UserInfo> infos = userInfoApi.findByIdss(userIds);
            //5、构造返回
            List<ListVo> vos = new ArrayList<>();
            for (int i = 0; i < visitors.size()-1; i++) {
                UserInfo userInfo = infos.get(i);
                if (userInfo != null) {
                    ListVo vo = ListVo.init(userInfo, aBoolean, visitors.get(i).getScore());
                    vos.add(vo);
                    redisTemplate.opsForHash().put(key,hashKey,new SimpleDateFormat("yyyyMMdd").format(new Date()));
                }
            }
            PageResult pr = new PageResult(page, pagesize, 0L, visitors);
            return pr;
        }
    }
}
